/**
* 
* Copyright [2007] [Sunny Liu]
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*/
package ${appConfig.outputPackageName}.xml;

import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ObjectXMLSerializerFactory 
{

	final Hashtable serializerMaps = new Hashtable();
	ObjectXMLSerializer defaultSerializer = null;
	private static Logger log = LoggerFactory.getLogger(ObjectXMLSerializerFactory.class);
		
	/**
	 * 
	 */
	public ObjectXMLSerializerFactory() 
	{
		super();
		defaultSerializer = new DefaultObjectXMLSerializer();
		ObjectXMLSerializer errorSerializer = new ErrorXMLSerializer();		
		serializerMaps.put(errorSerializer.supportedObject(), errorSerializer);
	}
	
	
	public void setObjectXMLSerializers(List list)
	{
		if(list==null) return;
		for(Iterator iterator=list.iterator(); iterator.hasNext(); )
		{
			
			ObjectXMLSerializer serializer = (ObjectXMLSerializer)iterator.next();
			if(log.isDebugEnabled()) log.debug("Adding XML Serializer for " + serializer.supportedObject().getName());
			
			serializerMaps.put(serializer.supportedObject(), serializer);
		}		
	}
	
	
	public ObjectXMLSerializer matchObjectXMLSerializer(Object object)
	{		
		
		Class clazz = object.getClass();
		if(object instanceof Collection && ((Collection)object).size()>0)
		{
			clazz = ((Collection)object).iterator().next().getClass();
		}		
		if(log.isDebugEnabled()) log.debug("Finding XML Serializer for " + clazz.getName());
		ObjectXMLSerializer serializer = (ObjectXMLSerializer)serializerMaps.get(clazz);
		if(serializer==null)
		{
			Class[] clazzs = object.getClass().getClasses();
			for(int i=0; i<clazzs.length; i++)
			{
				if(log.isDebugEnabled()) log.debug("Finding XML Serializer for " + clazzs[i]);
				serializer = (ObjectXMLSerializer)serializerMaps.get(clazzs[i]);
				if(serializer!=null) break; 
			}			
		}		
		
		if(serializer==null) {
			if(log.isDebugEnabled()) log.debug("Using default XML Serializer for " + clazz.getName());
			serializer = defaultSerializer;
		}
		return serializer;
	}

}